<template>
    <section class="todoapp">

    <TodoHeader :arr="list"
                @on="onFn"
    ></TodoHeader>

    <TodoMain :arr="showList"
              @del="delFn"
    ></TodoMain>

    <TodoFooter :arr="list"
                @change="changeFn"
                @clear="clearFn"
    ></TodoFooter>

    </section>
</template>

<script>
// 样式引入 + 导入组件并注册使用
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'

import './styles/base.css'
import './styles/index.css'

export default {

    components: {
        TodoHeader,
        TodoMain,
        TodoFooter
    },

    data() {
        return {
            list: JSON.parse(localStorage.getItem('todos')) || [],
            type: ''
        }
    },
    methods: {
        delFn(id){
            this.list = this.list.filter(item => item.id !== id)
        },
        onFn(name){
            this.list.unshift({
                id: parseInt(Math.random()*999+1),
                name,
                isDone: false
            })
        },
        changeFn(type){
            this.type = type
        },
        clearFn(){
            this.list = this.list.filter(item => item.isDone !== true)
        }
    },
    computed: {
        showList(){
            if(this.type === 'active'){
                return this.list.filter(item => item.isDone === true)
            } else if(this.type === 'completed'){
                return this.list.filter(item => item.isDone !== true)
            } else {
                return this.list
            }
        }
    },
    watch: {
        list:{
            deep: true,
            handler(){
                localStorage.setItem("todos",JSON.stringify(this.list))
            }
        }
    }
}
</script>
